using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System.Text;

namespace _RobotInspection.Controllers
{
    /// <summary>
    /// 实体生成控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class EntityGeneratorController : ControllerBase
    {
        private readonly ISqlSugarClient _db;
        private readonly ILogger<EntityGeneratorController> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="db"></param>
        /// <param name="logger"></param>
        public EntityGeneratorController(ISqlSugarClient db, ILogger<EntityGeneratorController> logger)
        {
            _db = db;
            _logger = logger;
        }

        /// <summary>
        /// 生成指定表的实体类
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <param name="outputPath">输出路径</param>
        /// <returns></returns>
        [HttpPost("generate-entity")]
        public IActionResult GenerateEntity([FromQuery] string tableName, [FromQuery] string outputPath = "")
        {
            try
            {
                if (string.IsNullOrEmpty(tableName))
                {
                    return BadRequest("表名不能为空");
                }

                if (string.IsNullOrEmpty(outputPath))
                {
                    outputPath = Path.Combine(Directory.GetCurrentDirectory(), "Entities");
                }

                // 确保输出目录存在
                if (!Directory.Exists(outputPath))
                {
                    Directory.CreateDirectory(outputPath);
                }

                // 生成实体类
                _db.DbFirst.Where(tableName).CreateClassFile(outputPath);

                _logger.LogInformation($"实体类 {tableName} 生成成功，输出路径：{outputPath}");
                return Ok(new { message = $"实体类 {tableName} 生成成功", outputPath });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成实体类时发生错误");
                return StatusCode(500, new { message = "生成实体类时发生错误", error = ex.Message });
            }
        }

        /// <summary>
        /// 生成所有表的实体类
        /// </summary>
        /// <param name="outputPath">输出路径</param>
        /// <param name="namespaceName">命名空间</param>
        /// <returns></returns>
        [HttpPost("generate-all-entities")]
        public IActionResult GenerateAllEntities([FromQuery] string outputPath = "", [FromQuery] string namespaceName = "BNAPositioning.Entities")
        {
            try
            {
                if (string.IsNullOrEmpty(outputPath))
                {
                    outputPath = Path.Combine(Directory.GetCurrentDirectory(), "Entities");
                }

                // 确保输出目录存在
                if (!Directory.Exists(outputPath))
                {
                    Directory.CreateDirectory(outputPath);
                }

                // 生成所有实体类
                _db.DbFirst.IsCreateDefaultValue().CreateClassFile(outputPath, namespaceName);

                _logger.LogInformation($"所有实体类生成成功，输出路径：{outputPath}");
                return Ok(new { message = "所有实体类生成成功", outputPath });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成所有实体类时发生错误");
                return StatusCode(500, new { message = "生成所有实体类时发生错误", error = ex.Message });
            }
        }

        /// <summary>
        /// 获取数据库中的所有表名
        /// </summary>
        /// <returns></returns>
        [HttpGet("tables")]
        public IActionResult GetTableNames()
        {
            try
            {
                var tableNames = _db.DbMaintenance.GetTableInfoList().Select(t => t.Name).ToList();
                return Ok(new { tables = tableNames });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取表名列表时发生错误");
                return StatusCode(500, new { message = "获取表名列表时发生错误", error = ex.Message });
            }
        }
    }
}